package top.hidoctor.auscultation.feature.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.tang.net.NetClient;
import com.tang.util.AppUtil;
import com.tang.util.BigDecimalUtil;
import com.tang.util.DensityUtil;
import com.tang.util.ImageUtil;
import com.tang.util.TimeUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.GailvAdapter;
import top.hidoctor.auscultation.adapter.PatientInfoAdapter;
import top.hidoctor.auscultation.adapter.SekaAdapter2;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.AnalysisBean;
import top.hidoctor.auscultation.bean.ScreenDetailBean;
import top.hidoctor.auscultation.event.AssessEvent;
import top.hidoctor.auscultation.net.c.ShaichaDetaiContract;
import top.hidoctor.auscultation.net.p.ShaichaDetailPresenter;
import top.hidoctor.auscultation.utils.GitImageOriginWidthAndHeight;
import top.hidoctor.auscultation.widget.Player2;

public class ShaichaDetailActivity extends BaseActivity implements View.OnClickListener, ShaichaDetaiContract.View {

    private RecyclerView rcContent, rcSeka, rcGl;

    private TextView tvMore, tvDetail, tvCode, tvAllTime, tvTime, tvJielun, tvAiStatus, tvJielunStatus, tvRemark, tvYangbenGl, tvYc;
    private boolean isMore = false;
    private PatientInfoAdapter patientInfoAdapter;
    private Button btnJieguo;
    private String id = "";
    private ShaichaDetailPresenter presenter;
    private LinearLayout llFenxizhong, llJielun, llFenxiContent;
    private String[] sekas = {"0", "dB", "-4", "-8", "-12", "-16", "-20", "-24", "-28", "-32", "-36", "-40", "-44", "-48", "-52", "-56", "-60", "-64"};
    private ImageView ivFxz;
    List<String> list = new ArrayList<>();
    List<AnalysisBean> glList = new ArrayList<>();
    private ImageView ivJxsb, ibBofang;
    private ImageView ivContent;
    private GailvAdapter gailvAdapter;
    private SeekBar seekBar;
    private String wavPath = "";
    private Player2 player;
    private int playStatus = 0;// 0 零状态  1 开始 2 暂停
    private ScreenDetailBean bean;
    private HorizontalScrollView hScrollView;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_shaicha_detail);
        EventBus.getDefault().register(this);
        initView();
        initEvent();

    }

    private void initEvent() {
        presenter = new ShaichaDetailPresenter(this, this);

        Intent intent = getIntent();
        if (intent.hasExtra("id")) {
            id = intent.getStringExtra("id");
            presenter.getDetail(id);
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.tv_title);
        TextView tvSetting = findViewById(R.id.tv_setting);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        tvTitle.setText("筛查详情");
        tvSetting.setText("查看结果");

        ibBofang = findViewById(R.id.ib_bofang);
        hScrollView = findViewById(R.id.h_scrollView);
        seekBar = findViewById(R.id.seekBar);
        rcSeka = findViewById(R.id.rc_seka);
        tvMore = findViewById(R.id.tv_more);
        btnJieguo = findViewById(R.id.btn_jieguo);
        tvDetail = findViewById(R.id.tv_detail);
        rcContent = findViewById(R.id.rc_content);
        tvCode = findViewById(R.id.tv_code);
        tvAllTime = findViewById(R.id.tv_all_time);
        tvTime = findViewById(R.id.tv_time);
        llFenxizhong = findViewById(R.id.ll_fenxizhong);
        llFenxiContent = findViewById(R.id.ll_fenxi_content);
        tvJielun = findViewById(R.id.tv_jielun);
        llJielun = findViewById(R.id.ll_jielun);
        tvAiStatus = findViewById(R.id.tv_ai_status);
        ivFxz = findViewById(R.id.iv_fxz);
        ivJxsb = findViewById(R.id.iv_jxsb);
        tvJielunStatus = findViewById(R.id.tv_jielun_status);
        tvRemark = findViewById(R.id.tv_remark);
        tvYangbenGl = findViewById(R.id.tv_yangben_gl);
        tvYc = findViewById(R.id.tv_yc);
        rcGl = findViewById(R.id.rc_gl);
        ivContent = findViewById(R.id.iv_content);
        rcContent.setLayoutManager(new LinearLayoutManager(this));
        rcContent.setAdapter(patientInfoAdapter = new PatientInfoAdapter(R.layout.item_patient_info, null));

        rcGl.setLayoutManager(new LinearLayoutManager(this));
        rcGl.setAdapter(gailvAdapter = new GailvAdapter(R.layout.item_gailv, null));

        rcSeka.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rcSeka.setAdapter(new SekaAdapter2(R.layout.item_seka, Arrays.asList(sekas)));
        tvMore.setOnClickListener(this);
        tvDetail.setOnClickListener(this);
        btnJieguo.setOnClickListener(this);
        btnJieguo.setOnClickListener(this);
        ibBofang.setOnClickListener(this);

        player = new Player2(seekBar);
        player.setOnplayerListener(new Player2.OnplayerListener() {
            @Override
            public void onCompletion() {
                //播放完成
                playStatus = 0;
                ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                tvTime.setText("/00:00");
            }
        });

//        hScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//                Log.e("TAG", "onScrollChange: " + scrollX);
//                int width = ivContent.getWidth();
//                Integer duration = bean.getScreeningDetail().getDuration();
//                double position = BigDecimalUtil.div(scrollX, width) * duration;
//                seekBar.setProgress((int) position);
//            }
//        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                final int currentPosition = seekBar.getProgress();
                tvTime.setText("/" + AppUtil.stringForTime2(currentPosition));
                Log.e("TAG", "onProgressChanged: " + seekBar.getProgress());
                int width = ivContent.getWidth();
                Integer duration = bean.getScreeningDetail().getDuration();
                hScrollView.smoothScrollTo((int) Math.round(BigDecimalUtil.div(currentPosition, duration) * width), 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                player.seekTo(seekBar.getProgress());
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_more:
                isMore = !isMore;
                if (isMore) {
                    patientInfoAdapter.setNewData(list);
                } else {
                    patientInfoAdapter.setNewData(list.size() > 2 ? list.subList(0, 2) : null);
                }
                break;
            case R.id.tv_detail:
                startActivity(new Intent(this, ShaichaPatientDetail.class));
                break;
            case R.id.btn_jieguo:
                startActivity(new Intent(this, ShaichaJieguoActivity.class).putExtra("id", id));
                break;
            case R.id.ib_bofang:
                if (TextUtils.isEmpty(wavPath)) {
                    showToast("文件获取异常");
                    return;
                }
                if (playStatus == 0) { // 播放状态
                    playStatus = 1;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            player.playUrl(wavPath);

                        }
                    }).start();
                    ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                } else if (playStatus == 1) {// 暂停状态
                    playStatus = 2;
                    if (player != null) {
                        player.pause();
                    }
                    ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                } else if (playStatus == 2) { //继续播放
                    playStatus = 1;
                    if (player != null) {
                        player.play();
                    }
                    ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                }

                break;
        }
    }


    @Override
    public void getDetailSuc(ScreenDetailBean bean) {
        if (bean != null) {
            this.bean = bean;
            tvCode.setText(bean.getNo());
            Integer aiStatus = bean.getAiStatus();
            list.clear();
            list.add("患者姓名：" + bean.getPatient().getName());
            list.add("监护者姓名：" + bean.getPatient().getGuardian());
            list.add("出生日期：" + TimeUtil.formatTime(bean.getPatient().getBirthday() + "", TimeUtil.Y_M_D));
            list.add("性别：" + (bean.getPatient().getGender() == 1 ? "男" : bean.getPatient().getGender() == 2 ? "女" : "保密"));
            list.add("门诊号：" + (TextUtils.isEmpty(bean.getPatientNo()) ? "" : bean.getPatientNo()));
            list.add("医保号：" + (bean.getPatient() != null && !TextUtils.isEmpty(bean.getPatient().getHeathCare()) ? bean.getPatient().getHeathCare() : ""));
            list.add("身份证号：" + (bean.getPatient() != null && !TextUtils.isEmpty(bean.getPatient().getIdCard()) ? bean.getPatient().getIdCard() : ""));
            list.add("手机号：" + (bean.getPatient() != null && !TextUtils.isEmpty(bean.getPatient().getPhone()) ? bean.getPatient().getPhone() : ""));
            list.add("联系地址：" + (bean.getPatient() != null && !TextUtils.isEmpty(bean.getPatient().getAddress()) ? bean.getPatient().getAddress() : ""));
            list.add("身高：" + (TextUtils.isEmpty(bean.getHeight()) ? "" : bean.getHeight()));
            list.add("体重：" + (TextUtils.isEmpty(bean.getWeight()) ? "" : bean.getWeight()));
            list.add("是否镇静：" + (bean.getCalm() == 1 ? "是" : "否"));
            list.add("体位：" + (TextUtils.isEmpty(bean.getPosition()) ? "" : bean.getPosition()));
            list.add("配合程度：" + (TextUtils.isEmpty(bean.getCoordinate()) ? "" : bean.getCoordinate()));
            list.add("心音采集场所：" + (TextUtils.isEmpty(bean.getSite()) ? "" : bean.getSite()));
            list.add("是否手术：" + (TextUtils.isEmpty(bean.getOperation()) ? "" : bean.getOperation()));
            list.add("临床诊断信息：" + (TextUtils.isEmpty(bean.getDescn()) ? "" : bean.getDescn()));
            list.add("备注：" + (TextUtils.isEmpty(bean.getRemark()) ? "" : bean.getRemark()));
            patientInfoAdapter.setNewData(list.subList(0, 2));
            if (aiStatus == 10) {//分析中
                llFenxizhong.setVisibility(View.VISIBLE);
                llFenxiContent.setVisibility(View.GONE);
                ivJxsb.setVisibility(View.GONE);
                ivFxz.setVisibility(View.VISIBLE);
                Glide.with(this).asGif().load(R.drawable.fxz).apply(new RequestOptions().fitCenter()).into(ivFxz);
                tvAiStatus.setText("分析中...");
            } else if (aiStatus == 20) {//分析完成
                llFenxizhong.setVisibility(View.GONE);
                llFenxiContent.setVisibility(View.VISIBLE);
            } else if (aiStatus == 30) {//分析失败
                llFenxizhong.setVisibility(View.VISIBLE);
                llFenxiContent.setVisibility(View.GONE);
                ivJxsb.setVisibility(View.VISIBLE);
                ivFxz.setVisibility(View.GONE);
                tvAiStatus.setText("无法解析");
            }
            if (bean.getStatus() == 10) { //10：筛查中；20：筛查完成；30：待确定
                llJielun.setVisibility(View.GONE);
                tvJielun.setVisibility(View.GONE);
                btnJieguo.setVisibility(View.VISIBLE);
            } else if (bean.getStatus() == 20) {
                llJielun.setVisibility(View.VISIBLE);
                tvJielun.setVisibility(View.VISIBLE);
                btnJieguo.setVisibility(View.GONE);
            }
            ScreenDetailBean.ScreeningAssessBean screeningAssess = bean.getScreeningAssess();
            if (screeningAssess != null) {
                String conditions = TextUtils.isEmpty(screeningAssess.getConditions()) ? "" : screeningAssess.getConditions();
                tvJielunStatus.setText(conditions.equals("0") ? "正常" : conditions.equals("1") ? "异常" : "待确定");//0：正常；1：异常；2：待确定
                tvRemark.setText("备注：" + screeningAssess.getRemake());
            }
            ScreenDetailBean.ScreeningAnalysisBean analysis = bean.getScreeningAnalysis();
            if (analysis != null) {
                glList.clear();
                glList.add(new AnalysisBean("VSD", analysis.getVsdProbability()));
                glList.add(new AnalysisBean("ASD", analysis.getAsdProbability()));
                glList.add(new AnalysisBean("PDA", analysis.getPdaProbability()));
                glList.add(new AnalysisBean("PS", analysis.getPsProbability()));
                glList.add(new AnalysisBean("TOF", analysis.getTofProbability()));
                tvYc.setText(analysis.getAbnormalArea());
                gailvAdapter.setNewData(glList);
            }

            final ScreenDetailBean.ScreeningDetailBean screeningDetail = bean.getScreeningDetail();
            seekBar.setMax(screeningDetail.getDuration());
            if (screeningDetail != null) {
                tvAllTime.setText(AppUtil.stringForTime(screeningDetail.getDuration()));
                GitImageOriginWidthAndHeight.getPicSize(NetClient.IMG_URL + screeningDetail.getWavPowerPics(), new GitImageOriginWidthAndHeight.OnPicListener() {
                    @Override
                    public void onImageSize(int width, int height) {
                        int heights = DensityUtil.dip2px(ShaichaDetailActivity.this, 180);
                        int widths = (int) (BigDecimalUtil.div(width, height) * heights);
                        Glide.with(ShaichaDetailActivity.this)
                                .load(NetClient.IMG_URL + screeningDetail.getWavPowerPics())
                                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).override(widths, heights))
                                .into(ivContent);
                    }
                });

                wavPath = NetClient.IMG_URL + screeningDetail.getWavPath();
            }
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AssessEvent event) {
        presenter.getDetail(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.stop();
        EventBus.getDefault().unregister(this);
    }

}

